package product;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;

/*1：读取products.xml中的商品信息，输出。
2：查找商品信息：根据输入的商品号，输出对应的商品信息。
3：修改products.xml，输入商品编号（productno）和库存数量，修改对应商品的数量（stockcount）；
没有找到商品号，给出错误提示消息。
*/
public class Dom4jParseProduct {
    private final static String path = "homework26\\src\\product\\products.xml";
    SAXReader reader = new SAXReader();
    Scanner input = new Scanner(System.in);
    Document document = null;

    public void save(Document document) {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        outputFormat.setEncoding("UTF-8");
        XMLWriter xmlWriter = null;
        try {
            xmlWriter = new XMLWriter(new FileWriter(path), outputFormat);
            xmlWriter.write(document);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                xmlWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void findAll() {
        try {
            document = reader.read(new File(path));
            Element rootEle = document.getRootElement();
            for (Iterator iterator = rootEle.elementIterator(); iterator.hasNext(); ) {
                Element productEle = (Element) iterator.next();
                for (Iterator it = productEle.elementIterator(); it.hasNext(); ) {
                    Element element = (Element) it.next();
                    switch (element.getName()) {
                        case "productno":
                            System.out.print("商品编号：" + element.getText());
                            break;
                        case "name":
                            System.out.print(",商品名称：" + element.getText());
                            break;
                        case "discount":
                            System.out.print(",商品折扣：" + element.getText());
                            break;
                        case "manufacturer":
                            System.out.print(",商品生产商：" + element.getText());
                            break;
                        case "price":
                            System.out.print(",商品单价：" + element.getText() + "元/" + element.attributeValue("unit"));
                            break;
                        case "stockcount":
                            System.out.print(",商品库存量：" + element.getText());
                            break;
                        default:
                            break;
                    }
                }
                System.out.println();
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Dom4jParseProduct dpp = new Dom4jParseProduct();
        dpp.findAll();
        dpp.find();
        dpp.modifier();
        dpp.purchase();
    }
    public void find() {
        System.out.print("请输入你想查询的商品号：");
        String productno = input.next();
        try {
            document = reader.read(new File(path));
            Element rootEle = document.getRootElement();
            for (Iterator iterator = rootEle.elementIterator(); iterator.hasNext(); ) {
                Element productEle = (Element) iterator.next();
                Element productnoEle = productEle.element("productno");
                if (productno.equals(productnoEle.getText())) {
                    //所有查询相似，但是这里有一个判断，和输入的商品号相同的才输出
                    System.out.print("商品编号：" + productEle.element("productno").getText());
                    System.out.print(",商品名称：" + productEle.element("name").getText());
                    System.out.print(",商品折扣：" + productEle.element("discount").getText());
                    System.out.print(",商品生产商：" + productEle.element("manufacturer").getText());
                    System.out.print(",商品单价：" + productEle.element("price").getText() + "元/" + productEle.element("price").attributeValue("unit"));
                    System.out.print(",商品库存量：" + productEle.element("stockcount").getText());
                    break;
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    /*修改products.xml，输入商品编号（productno）和库存数量，修改对应商品的数量（stockcount）；
    没有找到商品号，给出错误提示消息。*/
    public void modifier(){
        System.out.print("\n请输入你想修改的商品号：");
        String productno = input.next();
        System.out.print("请输入你想修改的商品数量：");
        int count = input.nextInt();
        boolean isExist = false;
        try {
            document = reader.read(new File(path));
            Element rootEle = document.getRootElement();
            for (Iterator iterator = rootEle.elementIterator(); iterator.hasNext();) {
                Element productEle = (Element)iterator.next();
                Element productnoEle = productEle.element("productno");//拿出商品的号码元素与输入的对比
                if (productno.equals(productnoEle.getText())) {
                    productEle.element("stockcount").setText(String.valueOf(count));
                    //找到目标后，再拿出它的库存元素再修改其值
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                System.out.println("对不起，没有此商品！");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        save(document);
    }
    /*以products.xml作为基础，实现客户购买的方法，输入商品号和购买数量，计算应付金额，如果是折扣商品，打七折；
    如果购买数量超过库存量，给出提示库存不足，如果购买成功，扣除相应的数量*/
    public void purchase(){
        System.out.print("请输入你想购买的商品号：");
        String productno = input.next();
        System.out.print("请输入你想购买的商品数量：");
        int buyCount = input.nextInt();
        double totalPrice = 0;
        boolean isExist = false;
        try {
            document = reader.read(new File(path));
            Element rootEle = document.getRootElement();
            for (Iterator iterator = rootEle.elementIterator(); iterator.hasNext();) {
                Element productEle = (Element)iterator.next();
                Element productnoEle = productEle.element("productno");//拿出商品的号码元素与输入的对比
                if (productno.equals(productnoEle.getText())) {
                    if (Integer.parseInt(productEle.element("stockcount").getText()) - buyCount >= 0) {
                        productEle.element("stockcount").setText(String.valueOf(Integer.parseInt(productEle.element("stockcount").getText()) - buyCount));
                        totalPrice = buyCount * Double.parseDouble(productEle.element("price").getText());
                        if (productEle.element("discount").getText().equals("七折")) {
                            totalPrice *= 0.7;
                        }
                    }else {
                        System.out.println("库存不足！");
                    }
                    //找到目标后，再拿出它的库存元素再修改其值
                    isExist = true;
                    break;
                }
            }
            System.out.println("你本次购物话费：" + totalPrice + "元");
            if (!isExist) {
                System.out.println("对不起，没有此商品！");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        save(document);
    }
}
